#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/config/functions"

trigger-builder-herokuish-builder-release() {
  declare desc="builder-herokuish builder-release plugin trigger"
  declare trigger="builder-release"
  declare BUILDER_TYPE="$1" APP="$2" IMAGE_TAG="$3"

  if [[ "$BUILDER_TYPE" != "herokuish" ]]; then
    return
  fi

  local CID
  local IMAGE=$(get_app_image_name "$APP" "$IMAGE_TAG")
  local DOCKER_COMMIT_LABEL_ARGS=("--change" "LABEL org.label-schema.schema-version=1.0" "--change" "LABEL org.label-schema.vendor=dokku" "--change" "LABEL com.dokku.app-name=$APP")
  local DOCKER_RUN_LABEL_ARGS="--label=com.dokku.app-name=$APP"

  plugn trigger pre-release-buildpack "$APP" "$IMAGE_TAG"
  if [[ -n $(config_export global) ]]; then
    CID=$(config_export global | "$DOCKER_BIN" container run "${DOCKER_RUN_LABEL_ARGS[@]}" $DOKKU_GLOBAL_RUN_ARGS -i -a stdin "$IMAGE" /bin/bash -c "mkdir -p /app/.profile.d && cat > /app/.profile.d/00-global-env.sh")
    if test "$("$DOCKER_BIN" container wait "$CID")" -ne 0; then
      dokku_log_warn "Failure injecting global environment variables"
      return 1
    fi

    "$DOCKER_BIN" container commit "${DOCKER_COMMIT_LABEL_ARGS[@]}" "$CID" "$IMAGE" >/dev/null
  fi
  if [[ -n $(config_export app "$APP") ]]; then
    CID=$(config_export app "$APP" | "$DOCKER_BIN" container run "${DOCKER_RUN_LABEL_ARGS[@]}" $DOKKU_GLOBAL_RUN_ARGS -i -a stdin "$IMAGE" /bin/bash -c "mkdir -p /app/.profile.d && cat > /app/.profile.d/01-app-env.sh")
    if test "$("$DOCKER_BIN" container wait "$CID")" -ne 0; then
      dokku_log_warn "Failure injecting app environment variables"
      return 1
    fi

    "$DOCKER_BIN" container commit "${DOCKER_COMMIT_LABEL_ARGS[@]}" "$CID" "$IMAGE" >/dev/null
  fi

  echo "FROM $IMAGE" | suppress_output "$DOCKER_BIN" image build --label=com.dokku.image-stage=release -t "$IMAGE" -
  plugn trigger post-release-buildpack "$APP" "$IMAGE_TAG"
}

trigger-builder-herokuish-builder-release "$@"
